<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>健康档案 - 营养健康系统</title>
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Marked.js for Markdown parsing -->
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <!-- Font Awesome CDN -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <!-- 自定义CSS -->
    <link rel="stylesheet" href="../css/styles.css">
</head>
<body class="bg-gray-50">
    <!-- 导航栏 -->
    <nav class="bg-green-600 text-white shadow-lg">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center">
                <svg class="h-10 w-10 mr-3" viewBox="0 0 100 100">
                    <circle cx="50" cy="50" r="45" fill="#4CAF50" />
                    <text x="50" y="55" font-size="20" text-anchor="middle" fill="white">营养</text>
                    <path d="M30,70 Q50,90 70,70" stroke="white" stroke-width="3" fill="none" />
                </svg>
                <h1 class="text-xl font-bold">营养健康系统</h1>
            </div>
            <div class="hidden md:flex space-x-6">
                <a href="../index.html" class="hover:text-green-200">
                    <i class="fas fa-home mr-1"></i>首页
                </a>
                <a href="food-analysis.html" class="hover:text-green-200">
                    <i class="fas fa-apple-alt mr-1"></i>食品分析
                </a>
                <a href="health-profile.html" class="hover:text-green-200 border-b-2 border-white">
                    <i class="fas fa-heartbeat mr-1"></i>健康档案
                </a>
                <a href="diet-records.html" class="hover:text-green-200">
                    <i class="fas fa-utensils mr-1"></i>饮食记录
                </a>
                <a href="nutrition-charts.html" class="hover:text-green-200">
                    <i class="fas fa-chart-pie mr-1"></i>营养图表
                </a>
                <a href="knowledge-graph.html" class="hover:text-green-200">
                    <i class="fas fa-project-diagram mr-1"></i>知识图谱
                </a>
            </div>
            <div class="flex items-center space-x-4 nav-user-section">
                <!-- 这里的内容将由auth.js动态更新 -->
                <a href="login.html" class="hover:text-green-200">登录</a>
                <a href="register.html" class="bg-white text-green-600 px-4 py-2 rounded-lg hover:bg-green-100">注册</a>
            </div>
        </div>
    </nav>

    <!-- 页面标题 -->
    <div class="bg-green-500 text-white py-8">
        <div class="container mx-auto px-4">
            <h2 class="text-3xl font-bold">健康档案</h2>
            <p class="mt-2">完善您的健康信息，获取个性化的营养建议</p>
        </div>
    </div>

    <!-- 主要内容 -->
    <div class="container mx-auto px-4 py-8">
        <!-- 健康档案表单和健康指标 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
            <!-- 左侧：个人信息 -->
            <div class="lg:col-span-2">
                <div class="bg-white p-6 rounded-lg shadow-md mb-8">
                    <h3 class="text-xl font-semibold mb-6 text-gray-800">基本信息</h3>

                    <form id="profile-form">
                        <!-- 基本信息 -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                            <div class="form-group">
                                <label for="fullName" class="form-label">姓名</label>
                                <input type="text" id="fullName" class="form-input" placeholder="请输入您的姓名" required>
                            </div>

                            <div class="form-group">
                                <label for="gender" class="form-label">性别</label>
                                <select id="gender" class="form-input" required>
                                    <option value="">请选择</option>
                                    <option value="MALE">男</option>
                                    <option value="FEMALE">女</option>
                                    <option value="OTHER">其他</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <label for="dateOfBirth" class="form-label">出生日期</label>
                                <input type="date" id="dateOfBirth" class="form-input" required>
                            </div>

                            <div class="form-group">
                                <label for="email" class="form-label">电子邮箱</label>
                                <input type="email" id="email" class="form-input" placeholder="example@email.com">
                            </div>
                        </div>

                        <h3 class="text-xl font-semibold mb-6 text-gray-800">身体数据</h3>

                        <!-- 身体数据 -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                            <div class="form-group">
                                <label for="height" class="form-label">身高 (cm)</label>
                                <input type="number" id="height" class="form-input" placeholder="例如：170" min="50" max="250" required>
                            </div>

                            <div class="form-group">
                                <label for="weight" class="form-label">体重 (kg)</label>
                                <input type="number" id="weight" class="form-input" placeholder="例如：65" min="20" max="300" step="0.1" required>
                            </div>

                            <div class="form-group">
                                <label for="targetWeight" class="form-label">目标体重 (kg)</label>
                                <input type="number" id="targetWeight" class="form-input" placeholder="例如：60" min="20" max="300" step="0.1">
                            </div>

                            <div class="form-group">
                                <label for="activityLevel" class="form-label">活动水平</label>
                                <select id="activityLevel" class="form-input" required>
                                    <option value="">请选择</option>
                                    <option value="SEDENTARY">久坐不动（几乎不运动）</option>
                                    <option value="LIGHTLY_ACTIVE">轻度活动（每周运动1-3次）</option>
                                    <option value="MODERATELY_ACTIVE">中度活动（每周运动3-5次）</option>
                                    <option value="VERY_ACTIVE">高度活动（每周运动6-7次）</option>
                                    <option value="EXTREMELY_ACTIVE">极度活动（每天高强度运动或体力劳动）</option>
                                </select>
                            </div>
                        </div>

                        <h3 class="text-xl font-semibold mb-6 text-gray-800">健康目标与限制</h3>

                        <!-- 健康目标与限制 -->
                        <div class="grid grid-cols-1 gap-6 mb-8">
                            <div class="form-group">
                                <label for="goal" class="form-label">健康目标</label>
                                <select id="goal" class="form-input" required>
                                    <option value="">请选择</option>
                                    <option value="LOSE_WEIGHT">减肥</option>
                                    <option value="MAINTAIN_WEIGHT">保持体重</option>
                                    <option value="GAIN_WEIGHT">增重</option>
                                    <option value="BUILD_MUSCLE">增肌</option>
                                    <option value="IMPROVE_HEALTH">改善健康</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <label for="healthConditions" class="form-label">健康状况（可多选）</label>
                                <div class="grid grid-cols-2 gap-2 mt-2">
                                    <label class="flex items-center">
                                        <input type="checkbox" class="mr-2 h-4 w-4 text-green-600" name="healthConditions" value="diabetes">
                                        <span>糖尿病</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="mr-2 h-4 w-4 text-green-600" name="healthConditions" value="hypertension">
                                        <span>高血压</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="mr-2 h-4 w-4 text-green-600" name="healthConditions" value="heart_disease">
                                        <span>心脏病</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="mr-2 h-4 w-4 text-green-600" name="healthConditions" value="high_cholesterol">
                                        <span>高胆固醇</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="mr-2 h-4 w-4 text-green-600" name="healthConditions" value="fatty_liver_disease">
                                        <span>脂肪肝</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="mr-2 h-4 w-4 text-green-600" name="healthConditions" value="gout">
                                        <span>痛风/高尿酸血症</span>
                                    </label>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="dietaryRestrictions" class="form-label">饮食限制（可多选）</label>
                                <div class="grid grid-cols-2 gap-2 mt-2">
                                    <label class="flex items-center">
                                        <input type="checkbox" class="mr-2 h-4 w-4 text-green-600" name="dietaryRestrictions" value="vegetarian">
                                        <span>素食主义</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="mr-2 h-4 w-4 text-green-600" name="dietaryRestrictions" value="vegan">
                                        <span>纯素食主义</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="mr-2 h-4 w-4 text-green-600" name="dietaryRestrictions" value="gluten_free">
                                        <span>无麸质</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="mr-2 h-4 w-4 text-green-600" name="dietaryRestrictions" value="lactose_free">
                                        <span>无乳糖</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="mr-2 h-4 w-4 text-green-600" name="dietaryRestrictions" value="Halal">
                                        <span>清真饮食</span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="checkbox" class="mr-2 h-4 w-4 text-green-600" name="dietaryRestrictions" value="Keto">
                                        <span>生酮饮食</span>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <!-- 提交按钮 -->
                        <div class="flex justify-end">
                            <button type="submit" class="bg-green-600 text-white px-6 py-3 rounded-lg hover:bg-green-700">保存健康档案</button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 右侧：健康指标 -->
            <div>
                <!-- 健康指标卡片 -->
                <div class="bg-white p-6 rounded-lg shadow-md mb-6">
                    <h3 class="text-xl font-semibold mb-4 text-gray-800">健康指标</h3>

                    <div class="mb-4">
                        <h4 class="font-medium text-gray-700 mb-2">BMI 指数</h4>
                        <div class="flex items-center">
                            <div class="w-12 h-12 rounded-full bg-green-100 text-green-600 flex items-center justify-center font-bold mr-3">
                                <span id="bmi-value">-</span>
                            </div>
                            <div>
                                <p id="bmi-status" class="font-medium">未计算</p>
                                <p class="text-sm text-gray-500">体重(kg) / 身高(m)²</p>
                            </div>
                        </div>
                    </div>

                    <div class="mb-4">
                        <h4 class="font-medium text-gray-700 mb-2">基础代谢率 (BMR)</h4>
                        <div class="flex items-center">
                            <div class="w-12 h-12 rounded-full bg-green-100 text-green-600 flex items-center justify-center font-bold mr-3">
                                <span id="bmr-value">-</span>
                            </div>
                            <div>
                                <p class="font-medium">卡路里/天</p>
                                <p class="text-sm text-gray-500">身体在休息状态下消耗的能量</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 营养需求卡片 -->
                <div class="bg-white p-6 rounded-lg shadow-md mb-6">
                    <h3 class="text-xl font-semibold mb-4 text-gray-800">每日营养需求</h3>

                    <div class="space-y-4">
                        <div>
                            <div class="flex justify-between mb-1">
                                <span class="font-medium text-gray-700">蛋白质</span>
                                <span id="protein-value" class="text-gray-600">- g</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div id="protein-bar" class="bg-green-600 h-2 rounded-full" style="width: 0%"></div>
                            </div>
                        </div>

                        <div>
                            <div class="flex justify-between mb-1">
                                <span class="font-medium text-gray-700">碳水化合物</span>
                                <span id="carbs-value" class="text-gray-600">- g</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div id="carbs-bar" class="bg-green-600 h-2 rounded-full" style="width: 0%"></div>
                            </div>
                        </div>

                        <div>
                            <div class="flex justify-between mb-1">
                                <span class="font-medium text-gray-700">脂肪</span>
                                <span id="fat-value" class="text-gray-600">- g</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div id="fat-bar" class="bg-green-600 h-2 rounded-full" style="width: 0%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 健康建议部分（单独一个模块） -->
        <div class="bg-white p-6 rounded-lg shadow-md mb-8">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-semibold text-gray-800">个性化健康建议</h3>
                <div class="flex space-x-2">
                    <button id="get-ai-advice-btn" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 text-sm flex items-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                        </svg>
                        获取健康建议(流式)
                    </button>
                    <button id="get-ai-advice-local-btn" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 text-sm flex items-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                        </svg>
                        获取健康建议(本地)
                    </button>
                </div>
            </div>

            <!-- AI建议加载指示器 -->
            <div id="ai-advice-loading" class="hidden mb-4">
                <div class="flex items-center">
                    <div class="spinner mr-3"></div>
                    <p>正在生成健康建议，请稍候...</p>
                </div>
            </div>

            <!-- 健康建议内容 -->
            <div id="health-advice" class="text-gray-500 markdown-content">
                请完善您的健康档案并点击"获取健康建议"按钮，获取个性化的健康建议。
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-green-800 text-white py-10 mt-12">
        <div class="container mx-auto px-4">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
                <div>
                    <h3 class="text-lg font-semibold mb-4">关于我们</h3>
                    <p class="text-green-200">营养健康系统致力于通过先进技术帮助用户了解食品营养成分，提供个性化健康建议。</p>
                </div>
                <div>
                    <h3 class="text-lg font-semibold mb-4">快速链接</h3>
                    <ul class="space-y-2 text-green-200">
                        <li><a href="../index.html" class="hover:text-white">首页</a></li>
                        <li><a href="food-analysis.html" class="hover:text-white">食品分析</a></li>
                        <li><a href="health-profile.html" class="hover:text-white">健康档案</a></li>
                        <li><a href="diet-records.html" class="hover:text-white">饮食记录</a></li>
                        <li><a href="nutrition-charts.html" class="hover:text-white">营养图表</a></li>
                        <li><a href="knowledge-graph.html" class="hover:text-white">知识图谱</a></li>
                    </ul>
                </div>
                <div>
                    <h3 class="text-lg font-semibold mb-4">联系我们</h3>
                    <ul class="space-y-2 text-green-200">
                        <li>邮箱：2541147551@nutrition-health.com</li>
                        <li>电话：400-123-4567</li>
                        <li>地址：丰和南大道696号</li>
                    </ul>
                </div>
                <div>
                    <h3 class="text-lg font-semibold mb-4">关注我们</h3>
                    <div class="flex space-x-4">
                        <a href="#" class="text-green-200 hover:text-white">
                            <svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M22.675 0h-21.35c-.732 0-1.325.593-1.325 1.325v21.351c0 .731.593 1.324 1.325 1.324h11.495v-9.294h-3.128v-3.622h3.128v-2.671c0-3.1 1.893-4.788 4.659-4.788 1.325 0 2.463.099 2.795.143v3.24l-1.918.001c-1.504 0-1.795.715-1.795 1.763v2.313h3.587l-.467 3.622h-3.12v9.293h6.116c.73 0 1.323-.593 1.323-1.325v-21.35c0-.732-.593-1.325-1.325-1.325z"/>
                            </svg>
                        </a>
                        <a href="#" class="text-green-200 hover:text-white">
                            <svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M23.953 4.57a10 10 0 01-2.825.775 4.958 4.958 0 002.163-2.723 10.054 10.054 0 01-3.127 1.184 4.92 4.92 0 00-8.384 4.482C7.69 8.095 4.067 6.13 1.64 3.162a4.822 4.822 0 00-.666 2.475c0 1.71.87 3.213 2.188 4.096a4.904 4.904 0 01-2.228-.616v.06a4.923 4.923 0 003.946 4.827 4.996 4.996 0 01-2.212.085 4.936 4.936 0 004.604 3.417 9.867 9.867 0 01-6.102 2.105c-.39 0-.779-.023-1.17-.067a13.995 13.995 0 007.557 2.209c9.053 0 13.998-7.496 13.998-13.985 0-.21 0-.42-.015-.63A9.935 9.935 0 0024 4.59z"/>
                            </svg>
                        </a>
                        <a href="#" class="text-green-200 hover:text-white">
                            <svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M12 0C8.74 0 8.333.015 7.053.072 5.775.132 4.905.333 4.14.63c-.789.306-1.459.717-2.126 1.384S.935 3.35.63 4.14C.333 4.905.131 5.775.072 7.053.012 8.333 0 8.74 0 12s.015 3.667.072 4.947c.06 1.277.261 2.148.558 2.913.306.788.717 1.459 1.384 2.126.667.666 1.336 1.079 2.126 1.384.766.296 1.636.499 2.913.558C8.333 23.988 8.74 24 12 24s3.667-.015 4.947-.072c1.277-.06 2.148-.262 2.913-.558.788-.306 1.459-.718 2.126-1.384.666-.667 1.079-1.335 1.384-2.126.296-.765.499-1.636.558-2.913.06-1.28.072-1.687.072-4.947s-.015-3.667-.072-4.947c-.06-1.277-.262-2.149-.558-2.913-.306-.789-.718-1.459-1.384-2.126C21.319 1.347 20.651.935 19.86.63c-.765-.297-1.636-.499-2.913-.558C15.667.012 15.26 0 12 0zm0 2.16c3.203 0 3.585.016 4.85.071 1.17.055 1.805.249 2.227.415.562.217.96.477 1.382.896.419.42.679.819.896 1.381.164.422.36 1.057.413 2.227.057 1.266.07 1.646.07 4.85s-.015 3.585-.074 4.85c-.061 1.17-.256 1.805-.421 2.227-.224.562-.479.96-.899 1.382-.419.419-.824.679-1.38.896-.42.164-1.065.36-2.235.413-1.274.057-1.649.07-4.859.07-3.211 0-3.586-.015-4.859-.074-1.171-.061-1.816-.256-2.236-.421-.569-.224-.96-.479-1.379-.899-.421-.419-.69-.824-.9-1.38-.165-.42-.359-1.065-.42-2.235-.045-1.26-.061-1.649-.061-4.844 0-3.196.016-3.586.061-4.861.061-1.17.255-1.814.42-2.234.21-.57.479-.96.9-1.381.419-.419.81-.689 1.379-.898.42-.166 1.051-.361 2.221-.421 1.275-.045 1.65-.06 4.859-.06l.045.03zm0 3.678c-3.405 0-6.162 2.76-6.162 6.162 0 3.405 2.76 6.162 6.162 6.162 3.405 0 6.162-2.76 6.162-6.162 0-3.405-2.76-6.162-6.162-6.162zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm7.846-10.405c0 .795-.646 1.44-1.44 1.44-.795 0-1.44-.646-1.44-1.44 0-.794.646-1.439 1.44-1.439.793-.001 1.44.645 1.44 1.439z"/>
                            </svg>
                        </a>
                    </div>
                </div>
            </div>
            <div class="border-t border-green-700 mt-8 pt-6 text-center text-green-300">
                <p>&copy; 2025 营养健康系统 版权所有</p>
            </div>
        </div>
    </footer>

    <!-- JavaScript -->
    <script src="../js/api-service.js"></script>
    <script src="../js/auth.js"></script>
    <script src="../js/main.js"></script>
    <script>
        // 健康档案页面特定脚本
        document.addEventListener('DOMContentLoaded', function() {
            const profileForm = document.getElementById('profile-form');
            const heightInput = document.getElementById('height');
            const weightInput = document.getElementById('weight');

            // 当前用户ID (实际应用中应从登录状态获取)
            const currentUserId = localStorage.getItem('userId') || 1; // 默认使用ID为1的用户

            // 加载用户健康档案
            async function loadHealthProfile() {
                try {
                    const profile = await apiService.healthProfile.getHealthProfile(currentUserId);
                    console.log('加载的健康档案数据:', profile);

                    if (profile) {
                        // 根据返回的数据结构确定如何访问字段
                        const healthProfile = profile.healthProfile || profile;
                        const user = profile.user || {};

                        // 填充表单数据
                        document.getElementById('fullName').value = user.fullName || '';
                        document.getElementById('gender').value = healthProfile.gender || '';
                        document.getElementById('dateOfBirth').value = healthProfile.dateOfBirth || '';
                        document.getElementById('email').value = user.email || '';
                        document.getElementById('height').value = healthProfile.height || '';
                        document.getElementById('weight').value = healthProfile.weight || '';
                        document.getElementById('targetWeight').value = healthProfile.targetWeight || '';
                        document.getElementById('activityLevel').value = healthProfile.activityLevel || '';
                        document.getElementById('goal').value = healthProfile.goal || '';

                        // 设置健康状况复选框
                        if (healthProfile.healthConditions) {
                            const healthConditions = healthProfile.healthConditions.split(', ');
                            document.querySelectorAll('input[name="healthConditions"]').forEach(checkbox => {
                                checkbox.checked = healthConditions.includes(checkbox.value);
                            });
                        }

                        // 设置饮食限制复选框
                        if (healthProfile.dietaryRestrictions) {
                            const dietaryRestrictions = healthProfile.dietaryRestrictions.split(', ');
                            document.querySelectorAll('input[name="dietaryRestrictions"]').forEach(checkbox => {
                                checkbox.checked = dietaryRestrictions.includes(checkbox.value);
                            });
                        }

                        // 加载健康指标
                        loadHealthMetrics();
                    }
                } catch (error) {
                    console.error('加载健康档案失败:', error);
                    showToast('加载健康档案失败，请稍后再试', 'error');
                }
            }

            // 加载健康指标
            async function loadHealthMetrics() {
                try {
                    // 获取BMI
                    const bmiData = await apiService.healthProfile.calculateBMI(currentUserId);
                    console.log('BMI数据:', bmiData);
                    if (bmiData) {
                        const bmiValue = document.getElementById('bmi-value');
                        const bmiStatus = document.getElementById('bmi-status');

                        bmiValue.textContent = bmiData.bmi;
                        bmiStatus.textContent = bmiData.category;

                        // 设置BMI状态样式
                        if (bmiData.category === '体重过轻') {
                            bmiStatus.className = 'font-medium text-blue-600';
                        } else if (bmiData.category === '正常范围' || bmiData.category === '正常体重') {
                            bmiStatus.className = 'font-medium text-green-600';
                        } else if (bmiData.category === '超重') {
                            bmiStatus.className = 'font-medium text-yellow-600';
                        } else {
                            bmiStatus.className = 'font-medium text-red-600';
                        }
                    }

                    // 获取BMR
                    const bmrData = await apiService.healthProfile.calculateBMR(currentUserId);
                    console.log('BMR数据:', bmrData);
                    if (bmrData) {
                        document.getElementById('bmr-value').textContent = Math.round(bmrData.bmr);
                    }

                    // 获取营养需求
                    const nutritionData = await apiService.healthProfile.getNutritionNeeds(currentUserId);
                    console.log('营养需求数据:', nutritionData);
                    if (nutritionData) {
                        // 提取营养数据，处理可能的不同数据结构
                        const protein = nutritionData.protein || 0;
                        const carbs = nutritionData.carbohydrates || nutritionData.carbs || 0;
                        const fat = nutritionData.fat || 0;

                        // 更新营养需求显示
                        document.getElementById('protein-value').textContent = `${Math.round(protein)} g`;
                        document.getElementById('carbs-value').textContent = `${Math.round(carbs)} g`;
                        document.getElementById('fat-value').textContent = `${Math.round(fat)} g`;

                        // 更新进度条
                        document.getElementById('protein-bar').style.width = '100%';
                        document.getElementById('carbs-bar').style.width = '100%';
                        document.getElementById('fat-bar').style.width = '100%';

                        // 更新健康建议
                        if (nutritionData.recommendations) {
                            const recommendations = Array.isArray(nutritionData.recommendations)
                                ? nutritionData.recommendations
                                : Object.values(nutritionData.recommendations);

                            document.getElementById('health-advice').innerHTML = recommendations
                                .map(rec => `<p class="mb-2">• ${rec}</p>`)
                                .join('');
                        }
                    }

                    // 获取健康建议（如果营养数据中没有）
                    if (!nutritionData?.recommendations) {
                        try {
                            const healthRecommendations = await apiService.healthProfile.getHealthRecommendations(currentUserId);
                            console.log('健康建议数据:', healthRecommendations);
                            if (healthRecommendations) {
                                const recommendations = Array.isArray(healthRecommendations)
                                    ? healthRecommendations
                                    : Object.values(healthRecommendations);

                                document.getElementById('health-advice').innerHTML = recommendations
                                    .map(rec => `<p class="mb-2">• ${rec}</p>`)
                                    .join('');
                            }
                        } catch (recError) {
                            console.error('获取健康建议失败:', recError);
                        }
                    }
                } catch (error) {
                    console.error('加载健康指标失败:', error);
                }
            }

            // 计算BMI和其他健康指标 (本地计算，用于实时反馈)
            function calculateHealthMetrics() {
                const height = parseFloat(heightInput.value);
                const weight = parseFloat(weightInput.value);

                if (height && weight) {
                    // 计算BMI
                    const heightInMeters = height / 100;
                    const bmi = weight / (heightInMeters * heightInMeters);
                    const bmiValue = document.getElementById('bmi-value');
                    const bmiStatus = document.getElementById('bmi-status');

                    bmiValue.textContent = bmi.toFixed(1);

                    // 设置BMI状态
                    if (bmi < 18.5) {
                        bmiStatus.textContent = '体重过轻';
                        bmiStatus.className = 'font-medium text-blue-600';
                    } else if (bmi < 24) {
                        bmiStatus.textContent = '正常范围';
                        bmiStatus.className = 'font-medium text-green-600';
                    } else if (bmi < 28) {
                        bmiStatus.textContent = '超重';
                        bmiStatus.className = 'font-medium text-yellow-600';
                    } else {
                        bmiStatus.textContent = '肥胖';
                        bmiStatus.className = 'font-medium text-red-600';
                    }
                }
            }

            // 监听输入变化
            heightInput.addEventListener('input', calculateHealthMetrics);
            weightInput.addEventListener('input', calculateHealthMetrics);

            // 表单提交处理
            profileForm.addEventListener('submit', async function(e) {
                e.preventDefault();

                // 收集表单数据
                const profileData = {
                    gender: document.getElementById('gender').value,
                    dateOfBirth: document.getElementById('dateOfBirth').value,
                    height: parseFloat(document.getElementById('height').value),
                    weight: parseFloat(document.getElementById('weight').value),
                    targetWeight: parseFloat(document.getElementById('targetWeight').value) || null,
                    activityLevel: document.getElementById('activityLevel').value,
                    goal: document.getElementById('goal').value,
                    healthConditions: Array.from(document.querySelectorAll('input[name="healthConditions"]:checked'))
                        .map(input => input.value),
                    dietaryRestrictions: Array.from(document.querySelectorAll('input[name="dietaryRestrictions"]:checked'))
                        .map(input => input.value)
                };

                // 用户基本信息
                const userData = {
                    fullName: document.getElementById('fullName').value,
                    email: document.getElementById('email').value
                };

                try {
                    // 显示加载状态
                    showToast('正在保存健康档案...', 'info');

                    // 保存健康档案
                    const saveData = {
                        ...profileData,
                        user: userData
                    };
                    console.log('保存的健康档案数据:', saveData);

                    const result = await apiService.healthProfile.saveHealthProfile(currentUserId, saveData);
                    console.log('保存结果:', result);

                    // 等待一小段时间，确保数据已经保存到数据库
                    setTimeout(async () => {
                        // 重新加载健康档案和健康指标
                        await loadHealthProfile();

                        // 显示成功消息
                        showToast('健康档案保存成功！', 'success');
                    }, 500);
                } catch (error) {
                    console.error('保存健康档案失败:', error);
                    showToast('保存失败，请稍后再试', 'error');
                }
            });

            // 获取AI健康建议按钮事件
            document.getElementById('get-ai-advice-btn').addEventListener('click', function() {
                getAIHealthAdvice();
            });
            
            // 获取本地模型AI健康建议按钮事件
            document.getElementById('get-ai-advice-local-btn').addEventListener('click', function() {
                getAIHealthAdviceLocal();
            });

            // 获取AI健康建议（流式）
            function getAIHealthAdvice() {
                const adviceContainer = document.getElementById('health-advice');
                const loadingIndicator = document.getElementById('ai-advice-loading');

                // 显示加载指示器
                loadingIndicator.classList.remove('hidden');

                // 清空之前的建议
                adviceContainer.innerHTML = '';
                adviceContainer.classList.remove('italic');

                // 创建一个临时容器来收集所有的内容
                let collectedContent = '';

                // 创建SSE连接
                const eventSource = apiService.healthProfile.getAIHealthAdvice(currentUserId, {
                    onMessage: (data) => {
                        // 收集内容
                        collectedContent += data;

                        // 尝试将Markdown转换为HTML并显示
                        try {
                            // 使用marked.js解析Markdown
                            const htmlContent = marked.parse(collectedContent);
                            adviceContainer.innerHTML = htmlContent;
                        } catch (e) {
                            // 如果解析失败，直接显示原始内容
                            console.error('Markdown解析失败:', e);
                            adviceContainer.innerHTML = collectedContent;
                        }

                        // 滚动到健康建议部分
                        window.scrollTo({
                            top: adviceContainer.offsetTop,
                            behavior: 'smooth'
                        });
                    },
                    onError: (event) => {
                        console.error('获取健康建议失败:', event);

                        // 隐藏加载指示器
                        loadingIndicator.classList.add('hidden');

                        // 显示错误信息
                        if (adviceContainer.innerHTML === '') {
                            adviceContainer.innerHTML = '获取健康建议失败，请稍后再试';
                            adviceContainer.classList.add('italic');
                        }

                        // 关闭连接
                        eventSource.close();
                    }
                });

                // 监听连接关闭
                eventSource.addEventListener('end', () => {
                    // 隐藏加载指示器
                    loadingIndicator.classList.add('hidden');
                    console.log('SSE连接已关闭');
                });
            }
            
            // 获取AI健康建议（本地模型，非流式）
            function getAIHealthAdviceLocal() {
                const adviceContainer = document.getElementById('health-advice');
                const loadingIndicator = document.getElementById('ai-advice-loading');
                
                // 显示加载指示器
                loadingIndicator.classList.remove('hidden');
                
                // 清空之前的建议
                adviceContainer.innerHTML = '';
                adviceContainer.classList.remove('italic');
                
                // 调用本地模型API
                apiService.healthProfile.getAIHealthAdviceLocal(currentUserId)
                    .then(response => {
                        // 隐藏加载指示器
                        loadingIndicator.classList.add('hidden');
                        
                        // 显示返回的建议
                        if (response && response.advice) {
                            // 尝试将Markdown转换为HTML并显示
                            try {
                                // 使用marked.js解析Markdown
                                const htmlContent = marked.parse(response.advice);
                                adviceContainer.innerHTML = htmlContent;
                            } catch (e) {
                                // 如果解析失败，直接显示原始内容
                                console.error('Markdown解析失败:', e);
                                adviceContainer.innerHTML = response.advice;
                            }
                        } else {
                            adviceContainer.innerHTML = '未能获取健康建议';
                            adviceContainer.classList.add('italic');
                        }
                        
                        // 滚动到健康建议部分
                        window.scrollTo({
                            top: adviceContainer.offsetTop,
                            behavior: 'smooth'
                        });
                    })
                    .catch(error => {
                        // 隐藏加载指示器
                        loadingIndicator.classList.add('hidden');
                        
                        // 显示错误信息
                        console.error('获取健康建议失败:', error);
                        adviceContainer.innerHTML = '获取健康建议失败，请稍后再试';
                        adviceContainer.classList.add('italic');
                    });
            }

            // 初始加载健康档案
            loadHealthProfile();
        });
    </script>
</body>
</html>
